package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备管理Service业务层处理
 *
 * @author Gzl
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备管理
     *
     * @param dto 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(DeviceDto dto) {
        String name = dto.getRemark();
        List<Device> devices = deviceMapper.selectList(Wrappers.<Device>lambdaQuery().eq(Device::getRemark, name).eq(Device::getProductName, dto.getProductName()));
        if (devices.size() > 0) {
            throw new BaseException("该老人已经有这个设备了");
        }

        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(String.valueOf(dto.getIotId()));
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(dto.getDeviceName());
        request.withBody(body);
        try {
            UpdateDeviceResponse response = client.updateDevice(request);
            if (response.getHttpStatusCode() != 200) {
                throw new BaseException("修改设备失败，HTTP状态码: " + response.getHttpStatusCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("修改设备失败");
        }


        Device device = new Device();
        BeanUtil.copyProperties(dto, device);
        return updateById(device) ? 1 : 0;

    }

    /**
     * 批量删除设备管理
     *
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备管理信息
     *
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(String id) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(id);


        try {
            DeleteDeviceResponse response = client.deleteDevice(request);
            if (response.getHttpStatusCode() != 204) {
                throw new BaseException("删除设备失败，HTTP状态码: " + response.getHttpStatusCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("删除设备失败");
        }
        return remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, id)) ? 1 : 0;
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        listProductsRequest.setLimit(50);
        ListProductsResponse listProductsResponse = client.listProducts(listProductsRequest);
        if (listProductsResponse.getHttpStatusCode() != 200) {
            throw new BaseException("同步产品列表失败");
        }
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(listProductsResponse.getProducts()));
    }

    /**
     * 查询所有产品列表
     */
    @Override
    public List<ProductVo> allProduct() {
        String jsonStr = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        if (StringUtils.isEmpty(jsonStr)) {
            return Collections.emptyList();
        }
        // 解析数据，并返回
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 注册设备
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //判断设备标识是否存在
        long count = count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()));
        if (count > 0) {
            throw new BaseException("设备标识码已存在");
        }
        //判断设备名称是否存在
        count = count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if (count > 0) {
            throw new BaseException("设备名称已存在");
        }
        //判断同一位置是否绑定了相同的产品
        count = count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(deviceDto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
        );
        if (count > 0) {
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
        //注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withProductId(deviceDto.getProductKey());
        body.withDeviceName(deviceDto.getDeviceName());
        body.withNodeId(deviceDto.getNodeId());

        // 秘钥设置,因为数据库表中也需要该字段
        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.withSecret(secret);
        body.withAuthInfo(authInfo);
        request.withBody(body);

        AddDeviceResponse response;
        try {
            response = client.addDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }
        // 本地保存设备
        // 属性拷贝
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        // 秘钥
        device.setSecret(secret);
        // 设备id、设备绑定状态
        device.setIotId(response.getDeviceId());
        this.save(device);

    }

    /**
     * 查询设备详情
     *
     * @param iotId 设备id
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //查询本地数据
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)) {
            return null;
        }
        //调用华为云接口查询设备详情
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }
        // 封装数据 返回给前端
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
        vo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            // 日期时区转换
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            // 日期时区转换
            vo.setActiveTime(DateTimeZoneConverter.utcToShanghai(activeTime));

        }
        return vo;
    }

    /**
     * 查询设备上报的数据
     *
     * @param iotId
     * @return
     */
    @Override
    public AjaxResult queryServiceProperties(String iotId) {

        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询设备影子，调用失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (ObjectUtil.isEmpty(shadow)) {
            return AjaxResult.success();
        }

        DeviceShadowProperties reported = shadow.get(0).getReported();
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());
        String eventTimeStr = reported.getEventTime();
        LocalDateTime eventTimeLocalDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeLocalDateTime);

        jsonObject.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", eventTime);
            list.add(map);
        });
        return AjaxResult.success(list);
    }

    /**
     * 查询产品详情
     *
     * @param productKey 产品的id
     * @return 产品详情
     */
    @Override
    public List<ServiceCapability> queryProduct(String productKey) {

        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);

        ShowProductResponse response;
        try {
            response = client.showProduct(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询产品详情，调用失败");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();


        return serviceCapabilities;
    }
}
